<template>
  <div class="comment-item">
    <div class="comment-user">
      <el-avatar :src="comment.userAvatar"/>
      <span class="username">{{ comment.username }}</span>
      <span class="time">{{ formatDateTime(comment.createTime) }}</span>
    </div>
    <div class="comment-content">{{ comment.content }}</div>
    <div class="comment-actions">
      <span class="action" @click="$emit('like', comment)">
        <el-icon>
          <Pointer/>
        </el-icon>
        {{ comment.likes }}
      </span>
      <span class="action" @click="$emit('reply', comment)">
        <el-icon><ChatDotRound/></el-icon>
        回复
      </span>
      <span v-if="hasChildren" class="action" @click="toggleCollapse">
        <el-icon>
          <component :is="isCollapsed ? 'ArrowDown' : 'ArrowUp'"/>
        </el-icon>
        {{ isCollapsed ? '展开' : '收起' }}
        <span class="comment-count">({{ comment.children.length }})</span>
      </span>
    </div>
    
    <!-- 递归渲染子评论 -->
    <div v-if="hasChildren && !isCollapsed" class="sub-comments">
      <CommentItem
        v-for="child in comment.children"
        :key="child.id"
        :comment="child"
        @like="$emit('like', $event)"
        @reply="$emit('reply', $event)"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Pointer, ChatDotRound, ArrowDown, ArrowUp } from '@element-plus/icons-vue'

const props = defineProps({
  comment: {
    type: Object,
    required: true
  }
})

defineEmits(['like', 'reply'])

const isCollapsed = ref(false)

const hasChildren = computed(() => {
  return props.comment.children && props.comment.children.length > 0
})

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.comment-item {
  padding: 15px;
  border-radius: 8px;
  background: #f5f7fa;
  margin-bottom: 15px;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.username {
  font-weight: bold;
  color: #303133;
}

.time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  margin: 10px 0;
}

.comment-actions {
  display: flex;
  gap: 20px;
}

.action {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.action:hover {
  color: #409EFF;
}

.comment-count {
  font-size: 12px;
  color: #909399;
}

.sub-comments {
  margin-top: 15px;
  margin-left: 30px;
  border-left: 2px solid #e4e7ed;
  padding-left: 15px;
}

.sub-comments .comment-item {
  background: #fff;
  margin-bottom: 10px;
}

.sub-comments .sub-comments {
  margin-left: 20px;
}
</style> 